const resizeHandlerMap = new WeakMap();
const dataWatcherMap = new WeakMap();

export default {
    // 解决设置表格多行之后如果有固定列，固定列不会随着表格的高度变化而变化
    inserted(el, _binding, vnode) {
        const table = vnode.componentInstance;

        if (table && table.$options._componentTag === 'el-table') {
            // 初次挂载时调用 doLayout
            table.$nextTick(() => {
                table.doLayout();
            });

            // 监听窗口大小变化
            const resizeHandler = () => {
                table.doLayout();
            };
            window.addEventListener('resize', resizeHandler);
            resizeHandlerMap.set(el, resizeHandler);

            // 监听数据变化
            const dataWatcher = table.$watch('data', () => {
                table.$nextTick(() => {
                    table.doLayout();
                });
            });
            dataWatcherMap.set(el, dataWatcher);
        }
    },
    unbind(el, _binding, vnode) {
        const table = vnode.componentInstance;

        if (table && table.$options._componentTag === 'el-table') {
            // 移除窗口大小变化监听
            const resizeHandler = resizeHandlerMap.get(el);
            if (resizeHandler) {
                window.removeEventListener('resize', resizeHandler);
                resizeHandlerMap.delete(el);
            }

            // 移除数据变化监听
            const dataWatcher = dataWatcherMap.get(el);
            if (dataWatcher) {
                dataWatcher();
                dataWatcherMap.delete(el);
            }
        }
    }
}
